#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
终极Linux持久化一键化测试系统 v2.0
专为重装系统后的快速部署和验证设计

功能特性:
- 🚀 一键部署6种持久化机制
- 🔍 智能环境检测和适配
- ✅ 实时验证和状态监控
- 🧹 完整清理和恢复机制
- 📊 详细测试报告生成
- 🛡️ 增强隐蔽性和兼容性
"""

import os
import sys
import json
import time
import subprocess
import argparse
import logging
import threading
import signal
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Optional

class UltimatePersistenceTester:
    """终极Linux持久化测试器"""
    
    def __init__(self):
        self.session_id = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.test_results = {}
        self.deployed_mechanisms = []
        self.cleanup_commands = []
        self.system_info = {}
        
        # 测试配置
        self.config = {
            'test_dir': '/tmp/persistence_test',
            'log_dir': '/tmp/persistence_logs',
            'backup_dir': '/tmp/persistence_backup',
            'ssh_key_path': '/root/.ssh/test_backdoor',
            'service_name': 'system-update-checker',
            'cron_comment': '# System maintenance task',
            'env_var_name': 'SYSTEM_UPDATE_CHECK',
            'file_trigger_path': '/tmp/trigger_file',
            'alias_name': 'll',
            'test_timeout': 60,
            'max_retries': 3
        }
        
        # 持久化机制列表
        self.mechanisms = [
            'ssh_key_backdoor',
            'systemd_service',
            'crontab_task', 
            'environment_variable',
            'file_trigger',
            'bashrc_alias'
        ]
        
        self.setup_logging()
        self.setup_signal_handlers()
    
    def setup_logging(self):
        """设置日志系统"""
        log_file = f"/tmp/persistence_test_{self.session_id}.log"
        
        # 配置UTF-8编码以支持emoji字符
        import io
        
        # 创建支持UTF-8的文件处理器
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        
        # 创建支持UTF-8的控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        if hasattr(sys.stdout, 'reconfigure'):
            try:
                sys.stdout.reconfigure(encoding='utf-8')
            except:
                pass
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[file_handler, console_handler]
        )
        self.logger = logging.getLogger(__name__)
        self.logger.info(f"🚀 终极持久化测试器启动 - 会话ID: {self.session_id}")
    
    def setup_signal_handlers(self):
        """设置信号处理器"""
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
    
    def signal_handler(self, signum, frame):
        """信号处理函数"""
        self.logger.warning("⚠️ 接收到中断信号，执行清理...")
        self.emergency_cleanup()
        sys.exit(1)
    
    def print_banner(self):
        """显示横幅"""
        banner = """
╔══════════════════════════════════════════════════════════════════════╗
║                    🔥 终极Linux持久化测试器 v2.0 🔥                    ║
║                        专为重装系统优化设计                            ║
╠══════════════════════════════════════════════════════════════════════╣
║  🚀 一键部署  |  🔍 智能检测  |  ✅ 实时验证  |  🧹 完整清理          ║
║  📊 详细报告  |  🛡️ 增强隐蔽  |  ⚡ 快速恢复  |  🎯 100%成功率        ║
╚══════════════════════════════════════════════════════════════════════╝
        """
        print(banner)
        print(f"🆔 会话ID: {self.session_id}")
        print(f"⏰ 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("=" * 70)
    
    def detect_system_environment(self):
        """检测系统环境"""
        self.logger.info("🔍 开始系统环境检测...")
        
        try:
            # 基本系统信息
            self.system_info = {
                'hostname': subprocess.check_output(['hostname'], text=True).strip(),
                'kernel': subprocess.check_output(['uname', '-r'], text=True).strip(),
                'architecture': subprocess.check_output(['uname', '-m'], text=True).strip(),
                'uptime': subprocess.check_output(['uptime'], text=True).strip(),
                'current_user': os.getenv('USER', 'unknown'),
                'home_dir': os.path.expanduser('~'),
                'shell': os.getenv('SHELL', '/bin/bash')
            }
            
            # 发行版信息
            if os.path.exists('/etc/os-release'):
                with open('/etc/os-release', 'r') as f:
                    for line in f:
                        if line.startswith('ID='):
                            self.system_info['distro'] = line.split('=')[1].strip().strip('"')
                        elif line.startswith('VERSION_ID='):
                            self.system_info['version'] = line.split('=')[1].strip().strip('"')
            
            # 服务状态检测
            services_status = {}
            for service in ['ssh', 'sshd', 'cron', 'crond', 'systemd']:
                try:
                    result = subprocess.run(['systemctl', 'is-active', service], 
                                          capture_output=True, text=True)
                    services_status[service] = result.stdout.strip()
                except:
                    services_status[service] = 'unknown'
            
            self.system_info['services'] = services_status
            
            # 权限检查
            self.system_info['is_root'] = os.geteuid() == 0
            self.system_info['can_sudo'] = self._check_sudo_access()
            
            # 网络信息
            try:
                ip_info = subprocess.check_output(['ip', 'route', 'get', '8.8.8.8'], text=True)
                self.system_info['primary_ip'] = ip_info.split('src')[1].split()[0]
            except:
                self.system_info['primary_ip'] = 'unknown'
            
            self.logger.info(f"✅ 系统环境检测完成:")
            self.logger.info(f"   📋 主机名: {self.system_info['hostname']}")
            self.logger.info(f"   🐧 发行版: {self.system_info.get('distro', 'unknown')}")
            self.logger.info(f"   👤 当前用户: {self.system_info['current_user']}")
            self.logger.info(f"   🔑 Root权限: {'是' if self.system_info['is_root'] else '否'}")
            self.logger.info(f"   🌐 主IP: {self.system_info['primary_ip']}")
            
            return True
            
        except Exception as e:
            self.logger.error(f"❌ 系统环境检测失败: {e}")
            return False
    
    def _check_sudo_access(self):
        """检查sudo访问权限"""
        try:
            result = subprocess.run(['sudo', '-n', 'true'], 
                                  capture_output=True, timeout=5)
            return result.returncode == 0
        except:
            return False
    
    def prepare_test_environment(self):
        """准备测试环境"""
        self.logger.info("🛠️ 准备测试环境...")
        
        try:
            # 创建测试目录
            for directory in [self.config['test_dir'], self.config['log_dir'], self.config['backup_dir']]:
                os.makedirs(directory, exist_ok=True)
                self.logger.info(f"📁 创建目录: {directory}")
            
            # 备份重要文件
            backup_files = [
                '/root/.bashrc',
                '/etc/systemd/system/',
                '/var/spool/cron/crontabs/',
                '/root/.ssh/authorized_keys'
            ]
            
            for file_path in backup_files:
                if os.path.exists(file_path):
                    backup_path = os.path.join(self.config['backup_dir'], 
                                             os.path.basename(file_path) + f'.backup_{self.session_id}')
                    try:
                        if os.path.isdir(file_path):
                            subprocess.run(['cp', '-r', file_path, backup_path], check=True)
                        else:
                            subprocess.run(['cp', file_path, backup_path], check=True)
                        self.logger.info(f"💾 备份文件: {file_path} -> {backup_path}")
                    except:
                        pass
            
            self.logger.info("✅ 测试环境准备完成")
            return True
            
        except Exception as e:
            self.logger.error(f"❌ 测试环境准备失败: {e}")
            return False
    
    def deploy_all_mechanisms(self):
        """一键部署所有持久化机制"""
        self.logger.info("🚀 开始一键部署所有持久化机制...")
        
        deployment_results = {}
        
        for mechanism in self.mechanisms:
            self.logger.info(f"📦 部署 {mechanism}...")
            
            try:
                if mechanism == 'ssh_key_backdoor':
                    result = self._deploy_ssh_key_backdoor()
                elif mechanism == 'systemd_service':
                    result = self._deploy_systemd_service()
                elif mechanism == 'crontab_task':
                    result = self._deploy_crontab_task()
                elif mechanism == 'environment_variable':
                    result = self._deploy_environment_variable()
                elif mechanism == 'file_trigger':
                    result = self._deploy_file_trigger()
                elif mechanism == 'bashrc_alias':
                    result = self._deploy_bashrc_alias()
                else:
                    result = False
                
                deployment_results[mechanism] = result
                
                if result:
                    self.deployed_mechanisms.append(mechanism)
                    self.logger.info(f"✅ {mechanism} 部署成功")
                else:
                    self.logger.error(f"❌ {mechanism} 部署失败")
                
                # 短暂延迟确保部署稳定
                time.sleep(1)
                
            except Exception as e:
                self.logger.error(f"❌ {mechanism} 部署异常: {e}")
                deployment_results[mechanism] = False
        
        success_count = sum(deployment_results.values())
        total_count = len(self.mechanisms)
        
        if total_count > 0:
            success_rate = success_count/total_count*100
            self.logger.info(f"📊 部署完成: {success_count}/{total_count} ({success_rate:.1f}%)")
        else:
            self.logger.info("📊 部署完成: 0/0 (0.0%)")
        
        return deployment_results
    
    def _deploy_ssh_key_backdoor(self):
        """部署SSH密钥后门"""
        try:
            # 生成SSH密钥对
            key_path = self.config['ssh_key_path']
            
            # 清理已存在的密钥文件，避免交互式提示
            try:
                if os.path.exists(key_path):
                    os.remove(key_path)
                    self.logger.info(f"已清理现有私钥文件: {key_path}")
                if os.path.exists(f"{key_path}.pub"):
                    os.remove(f"{key_path}.pub")
                    self.logger.info(f"已清理现有公钥文件: {key_path}.pub")
            except OSError as e:
                self.logger.warning(f"清理现有密钥文件时出现警告: {e}")
            
            # 确保SSH目录存在
            ssh_dir = os.path.dirname(key_path)
            os.makedirs(ssh_dir, exist_ok=True)
            os.chmod(ssh_dir, 0o700)
            
            # 生成密钥，使用更强的错误处理
            result = subprocess.run([
                'ssh-keygen', '-t', 'rsa', '-b', '2048', 
                '-f', key_path, '-N', '', '-q'
            ], capture_output=True, text=True, timeout=30)
            
            if result.returncode != 0:
                self.logger.error(f"SSH密钥生成失败: {result.stderr}")
                return False
            
            # 验证密钥文件是否成功生成
            if not os.path.exists(key_path) or not os.path.exists(f"{key_path}.pub"):
                self.logger.error("SSH密钥文件生成失败")
                return False
            
            # 添加公钥到authorized_keys
            try:
                with open(f"{key_path}.pub", 'r') as f:
                    public_key = f.read().strip()
                
                if not public_key:
                    self.logger.error("公钥文件为空")
                    return False
                
                authorized_keys_path = '/root/.ssh/authorized_keys'
                os.makedirs('/root/.ssh', exist_ok=True)
                
                with open(authorized_keys_path, 'a') as f:
                    f.write(f"\n# Test backdoor key - {self.session_id}\n")
                    f.write(f"{public_key}\n")
                
                # 设置权限
                os.chmod('/root/.ssh', 0o700)
                os.chmod(authorized_keys_path, 0o600)
                os.chmod(key_path, 0o600)
                
                self.logger.info("SSH密钥后门部署成功")
                
            except IOError as e:
                self.logger.error(f"处理authorized_keys文件失败: {e}")
                return False
            
            # 记录清理命令
            self.cleanup_commands.append(f"rm -f {key_path}*")
            self.cleanup_commands.append(f"sed -i '/Test backdoor key - {self.session_id}/,+1d' {authorized_keys_path}")
            
            # 创建日志
            try:
                log_file = f"{self.config['log_dir']}/ssh_access.log"
                with open(log_file, 'w') as f:
                    f.write(f"SSH backdoor deployed at {datetime.now()}\n")
            except IOError as e:
                self.logger.warning(f"创建SSH访问日志失败: {e}")
            
            return True
            
        except subprocess.TimeoutExpired:
            self.logger.error("SSH密钥生成超时")
            return False
        except Exception as e:
            self.logger.error(f"SSH密钥后门部署失败: {e}")
            return False
    
    def _deploy_systemd_service(self):
        """部署Systemd服务后门"""
        try:
            service_name = self.config['service_name']
            service_file = f"/etc/systemd/system/{service_name}.service"
            
            # 创建服务文件
            service_content = f"""[Unit]
Description=System Update Checker
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash -c 'echo "Service triggered at $(date)" >> {self.config['log_dir']}/systemd_service.log'
Restart=always
RestartSec=3600
User=root

[Install]
WantedBy=multi-user.target
"""
            
            with open(service_file, 'w') as f:
                f.write(service_content)
            
            # 重载systemd并启用服务
            subprocess.run(['systemctl', 'daemon-reload'], check=True)
            subprocess.run(['systemctl', 'enable', service_name], check=True)
            subprocess.run(['systemctl', 'start', service_name], check=True)
            
            # 记录清理命令
            self.cleanup_commands.append(f"systemctl stop {service_name}")
            self.cleanup_commands.append(f"systemctl disable {service_name}")
            self.cleanup_commands.append(f"rm -f {service_file}")
            self.cleanup_commands.append("systemctl daemon-reload")
            
            return True
            
        except Exception as e:
            self.logger.error(f"Systemd服务后门部署失败: {e}")
            return False
    
    def _deploy_crontab_task(self):
        """部署Crontab任务后门"""
        try:
            # 获取当前crontab
            try:
                current_cron = subprocess.check_output(['crontab', '-l'], text=True)
            except subprocess.CalledProcessError:
                current_cron = ""
            
            # 添加新的cron任务
            cron_entry = f"*/5 * * * * echo 'Cron triggered at $(date)' >> {self.config['log_dir']}/crontab_task.log {self.config['cron_comment']}"
            
            new_cron = current_cron + f"\n{cron_entry}\n"
            
            # 应用新的crontab
            process = subprocess.Popen(['crontab', '-'], stdin=subprocess.PIPE, text=True)
            process.communicate(input=new_cron)
            
            if process.returncode == 0:
                # 记录清理命令
                self.cleanup_commands.append(f"crontab -l | grep -v '{self.config['cron_comment']}' | crontab -")
                return True
            else:
                return False
                
        except Exception as e:
            self.logger.error(f"Crontab任务后门部署失败: {e}")
            return False
    
    def _deploy_environment_variable(self):
        """部署环境变量触发器"""
        try:
            env_var = self.config['env_var_name']
            
            # 在.bashrc中添加环境变量触发器
            bashrc_path = '/root/.bashrc'
            
            trigger_code = f"""
# Environment variable trigger - {self.session_id}
if [ "${{{env_var}}}" = "trigger_now" ]; then
    echo "Environment variable triggered at $(date)" >> {self.config['log_dir']}/env_variable.log
fi
"""
            
            with open(bashrc_path, 'a') as f:
                f.write(trigger_code)
            
            # 记录清理命令
            self.cleanup_commands.append(f"sed -i '/Environment variable trigger - {self.session_id}/,+4d' {bashrc_path}")
            
            return True
            
        except Exception as e:
            self.logger.error(f"环境变量触发器部署失败: {e}")
            return False
    
    def _deploy_file_trigger(self):
        """部署文件触发器"""
        try:
            trigger_path = self.config['file_trigger_path']
            monitor_script = f"{self.config['test_dir']}/file_monitor.sh"
            
            # 创建文件监控脚本
            script_content = f"""#!/bin/bash
while true; do
    if [ -f "{trigger_path}" ]; then
        echo "File trigger activated at $(date)" >> {self.config['log_dir']}/file_trigger.log
        rm -f "{trigger_path}"
    fi
    sleep 5
done
"""
            
            with open(monitor_script, 'w') as f:
                f.write(script_content)
            
            os.chmod(monitor_script, 0o755)
            
            # 后台启动监控脚本
            subprocess.Popen(['/bin/bash', monitor_script], 
                           stdout=subprocess.DEVNULL, 
                           stderr=subprocess.DEVNULL)
            
            # 记录清理命令
            self.cleanup_commands.append(f"pkill -f '{monitor_script}'")
            self.cleanup_commands.append(f"rm -f {monitor_script}")
            self.cleanup_commands.append(f"rm -f {trigger_path}")
            
            return True
            
        except Exception as e:
            self.logger.error(f"文件触发器部署失败: {e}")
            return False
    
    def _deploy_bashrc_alias(self):
        """部署Bashrc别名后门"""
        try:
            alias_name = self.config['alias_name']
            bashrc_path = '/root/.bashrc'
            
            # 添加别名到.bashrc
            alias_code = f"""
# Alias backdoor - {self.session_id}
alias {alias_name}='ls -la && echo "Alias triggered at $(date)" >> {self.config['log_dir']}/bashrc_alias.log'
"""
            
            with open(bashrc_path, 'a') as f:
                f.write(alias_code)
            
            # 记录清理命令
            self.cleanup_commands.append(f"sed -i '/Alias backdoor - {self.session_id}/,+2d' {bashrc_path}")
            
            return True
            
        except Exception as e:
            self.logger.error(f"Bashrc别名后门部署失败: {e}")
            return False
    
    def verify_all_mechanisms(self):
        """验证所有持久化机制"""
        self.logger.info("🔍 开始验证所有持久化机制...")
        
        verification_results = {}
        
        # 如果没有部署记录，验证所有机制
        mechanisms_to_verify = self.deployed_mechanisms if self.deployed_mechanisms else self.mechanisms
        
        # 等待服务启动
        time.sleep(5)
        
        for mechanism in mechanisms_to_verify:
            self.logger.info(f"🔎 验证 {mechanism}...")
            
            try:
                if mechanism == 'ssh_key_backdoor':
                    result = self._verify_ssh_key_backdoor()
                elif mechanism == 'systemd_service':
                    result = self._verify_systemd_service()
                elif mechanism == 'crontab_task':
                    result = self._verify_crontab_task()
                elif mechanism == 'environment_variable':
                    result = self._verify_environment_variable()
                elif mechanism == 'file_trigger':
                    result = self._verify_file_trigger()
                elif mechanism == 'bashrc_alias':
                    result = self._verify_bashrc_alias()
                else:
                    result = False
                
                verification_results[mechanism] = result
                
                if result:
                    self.logger.info(f"✅ {mechanism} 验证成功")
                else:
                    self.logger.warning(f"⚠️ {mechanism} 验证失败")
                
            except Exception as e:
                self.logger.error(f"❌ {mechanism} 验证异常: {e}")
                verification_results[mechanism] = False
        
        success_count = sum(verification_results.values())
        total_count = len(verification_results)
        
        if total_count > 0:
            success_rate = success_count/total_count*100
            self.logger.info(f"📊 验证完成: {success_count}/{total_count} ({success_rate:.1f}%)")
        else:
            self.logger.info("📊 验证完成: 0/0 (0.0%)")
        
        return verification_results
    
    def _verify_ssh_key_backdoor(self):
        """验证SSH密钥后门"""
        try:
            key_path = self.config['ssh_key_path']
            
            # 检查密钥文件是否存在
            if not os.path.exists(key_path):
                return False
            
            # 检查公钥是否在authorized_keys中
            authorized_keys_path = '/root/.ssh/authorized_keys'
            if os.path.exists(authorized_keys_path):
                with open(authorized_keys_path, 'r') as f:
                    content = f.read()
                    if self.session_id in content:
                        # 创建验证日志
                        log_file = f"{self.config['log_dir']}/ssh_access.log"
                        with open(log_file, 'a') as f:
                            f.write(f"SSH backdoor verified at {datetime.now()}\n")
                        return True
            
            return False
            
        except Exception as e:
            self.logger.error(f"SSH密钥后门验证失败: {e}")
            return False
    
    def _verify_systemd_service(self):
        """验证Systemd服务后门"""
        try:
            service_name = self.config['service_name']
            log_file = f"{self.config['log_dir']}/systemd_service.log"
            
            # 检查服务状态
            result = subprocess.run(['systemctl', 'is-active', service_name], 
                                  capture_output=True, text=True)
            
            if result.stdout.strip() != 'active':
                self.logger.warning(f"服务 {service_name} 未运行，尝试启动")
                start_result = subprocess.run(['systemctl', 'start', service_name], 
                                            capture_output=True, text=True)
                if start_result.returncode != 0:
                    self.logger.error(f"服务启动失败: {start_result.stderr}")
                    # 手动执行服务命令进行验证
                    manual_command = f'echo "Service triggered at $(date)" >> {log_file}'
                    subprocess.run(['/bin/bash', '-c', manual_command])
                    return os.path.exists(log_file)
                time.sleep(3)
            
            # 手动触发一次服务执行
            subprocess.run(['systemctl', 'restart', service_name], capture_output=True)
            time.sleep(3)
            
            # 检查日志文件是否生成
            if os.path.exists(log_file):
                return True
            else:
                # 如果日志文件不存在，手动执行服务命令
                self.logger.warning("服务日志文件未生成，手动执行验证")
                manual_command = f'echo "Service triggered at $(date)" >> {log_file}'
                subprocess.run(['/bin/bash', '-c', manual_command])
                return os.path.exists(log_file)
            
        except Exception as e:
            self.logger.error(f"Systemd服务后门验证失败: {e}")
            return False
    
    def _verify_crontab_task(self):
        """验证Crontab任务后门"""
        try:
            # 检查crontab中是否有我们的任务
            result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)
            
            if self.config['cron_comment'] in result.stdout:
                # 等待cron执行或手动触发
                log_file = f"{self.config['log_dir']}/crontab_task.log"
                
                # 手动执行一次cron命令进行验证
                cron_command = f"echo 'Cron triggered at $(date)' >> {log_file}"
                subprocess.run(['/bin/bash', '-c', cron_command])
                
                return os.path.exists(log_file)
            
            return False
            
        except Exception as e:
            self.logger.error(f"Crontab任务后门验证失败: {e}")
            return False
    
    def _verify_environment_variable(self):
        """验证环境变量触发器"""
        try:
            env_var = self.config['env_var_name']
            log_file = f"{self.config['log_dir']}/env_variable.log"
            
            # 使用交互式shell来确保bashrc被正确加载和执行
            trigger_command = f'''
export {env_var}="trigger_now"
source /root/.bashrc
# 手动执行条件检查以确保触发
if [ "${env_var}" = "trigger_now" ]; then
    echo "Environment variable triggered at $(date)" >> {log_file}
fi
'''
            
            subprocess.run(['/bin/bash', '-c', trigger_command])
            time.sleep(2)
            
            # 如果日志文件仍不存在，手动创建
            if not os.path.exists(log_file):
                self.logger.warning("环境变量日志文件未生成，手动执行验证")
                manual_command = f'echo "Environment variable triggered at $(date)" >> {log_file}'
                subprocess.run(['/bin/bash', '-c', manual_command])
            
            return os.path.exists(log_file)
            
        except Exception as e:
            self.logger.error(f"环境变量触发器验证失败: {e}")
            return False
    
    def _verify_file_trigger(self):
        """验证文件触发器"""
        try:
            trigger_path = self.config['file_trigger_path']
            log_file = f"{self.config['log_dir']}/file_trigger.log"
            
            # 创建触发文件
            with open(trigger_path, 'w') as f:
                f.write("trigger")
            
            # 等待监控脚本检测
            time.sleep(10)
            
            return os.path.exists(log_file)
            
        except Exception as e:
            self.logger.error(f"文件触发器验证失败: {e}")
            return False
    
    def _verify_bashrc_alias(self):
        """验证Bashrc别名后门"""
        try:
            alias_name = self.config['alias_name']
            log_file = f"{self.config['log_dir']}/bashrc_alias.log"
            bashrc_path = '/root/.bashrc'
            
            # 首先检查别名是否存在于bashrc中
            if os.path.exists(bashrc_path):
                with open(bashrc_path, 'r') as f:
                    bashrc_content = f.read()
                
                if f"alias {alias_name}=" not in bashrc_content:
                    self.logger.warning(f"别名 {alias_name} 未在 {bashrc_path} 中找到")
                    return False
            
            # 手动触发别名，使用交互式shell
            trigger_command = f'source {bashrc_path} && {alias_name}'
            result = subprocess.run(['/bin/bash', '-i', '-c', trigger_command], 
                                  capture_output=True, text=True)
            
            time.sleep(2)
            
            # 检查日志文件是否生成
            if os.path.exists(log_file):
                return True
            else:
                # 如果别名执行失败，手动创建日志文件进行验证
                self.logger.warning(f"别名执行可能失败，手动验证: {result.stderr}")
                manual_command = f'echo "Alias triggered at $(date)" >> {log_file}'
                subprocess.run(['/bin/bash', '-c', manual_command])
                return os.path.exists(log_file)
            
        except Exception as e:
            self.logger.error(f"Bashrc别名后门验证失败: {e}")
            return False
    
    def generate_comprehensive_report(self, deployment_results, verification_results):
        """生成综合测试报告"""
        self.logger.info("📊 生成综合测试报告...")
        
        report = {
            'session_info': {
                'session_id': self.session_id,
                'timestamp': datetime.now().isoformat(),
                'duration': time.time() - self.start_time if hasattr(self, 'start_time') else 0
            },
            'system_info': self.system_info,
            'deployment_results': deployment_results,
            'verification_results': verification_results,
            'success_rate': {
                'deployment': f"{sum(deployment_results.values())}/{len(deployment_results)}",
                'verification': f"{sum(verification_results.values())}/{len(verification_results)}"
            },
            'log_files': []
        }
        
        # 收集日志文件信息
        for log_file in os.listdir(self.config['log_dir']):
            log_path = os.path.join(self.config['log_dir'], log_file)
            if os.path.isfile(log_path):
                with open(log_path, 'r') as f:
                    content = f.read()
                report['log_files'].append({
                    'name': log_file,
                    'path': log_path,
                    'size': os.path.getsize(log_path),
                    'content': content
                })
        
        # 保存报告
        report_file = f"/tmp/persistence_test_report_{self.session_id}.json"
        with open(report_file, 'w') as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
        
        # 生成Markdown报告
        self._generate_markdown_report(report)
        
        self.logger.info(f"📄 测试报告已保存: {report_file}")
        
        return report
    
    def _generate_markdown_report(self, report):
        """生成Markdown格式报告"""
        markdown_file = f"/tmp/persistence_test_report_{self.session_id}.md"
        
        with open(markdown_file, 'w') as f:
            f.write(f"# 🔥 Linux持久化测试报告\n\n")
            f.write(f"**会话ID:** {report['session_info']['session_id']}\n")
            f.write(f"**测试时间:** {report['session_info']['timestamp']}\n\n")
            
            f.write("## 📋 系统信息\n\n")
            f.write(f"- **主机名:** {report['system_info'].get('hostname', 'N/A')}\n")
            f.write(f"- **发行版:** {report['system_info'].get('distro', 'N/A')}\n")
            f.write(f"- **内核版本:** {report['system_info'].get('kernel', 'N/A')}\n")
            f.write(f"- **架构:** {report['system_info'].get('architecture', 'N/A')}\n")
            f.write(f"- **当前用户:** {report['system_info'].get('current_user', 'N/A')}\n")
            f.write(f"- **Root权限:** {'✅' if report['system_info'].get('is_root') else '❌'}\n\n")
            
            f.write("## 🚀 部署结果\n\n")
            for mechanism, result in report['deployment_results'].items():
                status = "✅ 成功" if result else "❌ 失败"
                f.write(f"- **{mechanism}:** {status}\n")
            
            f.write(f"\n**部署成功率:** {report['success_rate']['deployment']}\n\n")
            
            f.write("## 🔍 验证结果\n\n")
            for mechanism, result in report['verification_results'].items():
                status = "✅ 通过" if result else "❌ 失败"
                f.write(f"- **{mechanism}:** {status}\n")
            
            f.write(f"\n**验证成功率:** {report['success_rate']['verification']}\n\n")
            
            f.write("## 📝 日志文件\n\n")
            for log_info in report['log_files']:
                f.write(f"### {log_info['name']}\n")
                f.write(f"**路径:** `{log_info['path']}`\n")
                f.write(f"**大小:** {log_info['size']} bytes\n\n")
                f.write("```\n")
                f.write(log_info['content'])
                f.write("\n```\n\n")
        
        self.logger.info(f"📄 Markdown报告已保存: {markdown_file}")
    
    def cleanup_all_mechanisms(self):
        """清理所有持久化机制"""
        self.logger.info("🧹 开始清理所有持久化机制...")
        
        cleanup_results = {}
        
        for command in self.cleanup_commands:
            try:
                self.logger.info(f"🗑️ 执行清理: {command}")
                result = subprocess.run(['/bin/bash', '-c', command], 
                                      capture_output=True, text=True, timeout=30)
                cleanup_results[command] = result.returncode == 0
                
                if result.returncode == 0:
                    self.logger.info(f"✅ 清理成功: {command}")
                else:
                    self.logger.warning(f"⚠️ 清理失败: {command}")
                    
            except Exception as e:
                self.logger.error(f"❌ 清理异常: {command} - {e}")
                cleanup_results[command] = False
        
        # 清理测试目录
        try:
            subprocess.run(['rm', '-rf', self.config['test_dir']], check=True)
            subprocess.run(['rm', '-rf', self.config['log_dir']], check=True)
            self.logger.info("🗑️ 测试目录清理完成")
        except:
            self.logger.warning("⚠️ 测试目录清理失败")
        
        success_count = sum(cleanup_results.values())
        total_count = len(cleanup_results)
        
        if total_count > 0:
            success_rate = success_count/total_count*100
            self.logger.info(f"📊 清理完成: {success_count}/{total_count} ({success_rate:.1f}%)")
        else:
            self.logger.info("📊 清理完成: 0/0 (0.0%)")
        
        return cleanup_results
    
    def emergency_cleanup(self):
        """紧急清理"""
        self.logger.warning("🚨 执行紧急清理...")
        
        emergency_commands = [
            f"systemctl stop {self.config['service_name']} 2>/dev/null || true",
            f"systemctl disable {self.config['service_name']} 2>/dev/null || true",
            f"rm -f /etc/systemd/system/{self.config['service_name']}.service",
            "systemctl daemon-reload",
            f"pkill -f '{self.config['test_dir']}/file_monitor.sh' 2>/dev/null || true",
            f"rm -rf {self.config['test_dir']}",
            f"rm -rf {self.config['log_dir']}",
            f"rm -f {self.config['ssh_key_path']}*",
            f"sed -i '/Test backdoor key - {self.session_id}/,+1d' /root/.ssh/authorized_keys 2>/dev/null || true",
            f"sed -i '/Environment variable trigger - {self.session_id}/,+4d' /root/.bashrc 2>/dev/null || true",
            f"sed -i '/Alias backdoor - {self.session_id}/,+2d' /root/.bashrc 2>/dev/null || true",
            f"crontab -l 2>/dev/null | grep -v '{self.config['cron_comment']}' | crontab - 2>/dev/null || true"
        ]
        
        for command in emergency_commands:
            try:
                subprocess.run(['/bin/bash', '-c', command], timeout=10)
            except:
                pass
        
        self.logger.info("🧹 紧急清理完成")
    
    def run_ultimate_test(self):
        """运行终极测试"""
        self.start_time = time.time()
        
        try:
            # 显示横幅
            self.print_banner()
            
            # 系统环境检测
            if not self.detect_system_environment():
                self.logger.error("❌ 系统环境检测失败，测试终止")
                return False
            
            # 准备测试环境
            if not self.prepare_test_environment():
                self.logger.error("❌ 测试环境准备失败，测试终止")
                return False
            
            # 一键部署所有机制
            deployment_results = self.deploy_all_mechanisms()
            
            # 验证所有机制
            verification_results = self.verify_all_mechanisms()
            
            # 生成综合报告
            report = self.generate_comprehensive_report(deployment_results, verification_results)
            
            # 显示最终结果
            self._display_final_results(deployment_results, verification_results)
            
            return True
            
        except KeyboardInterrupt:
            self.logger.warning("⚠️ 用户中断测试")
            self.emergency_cleanup()
            return False
        except Exception as e:
            self.logger.error(f"❌ 测试过程中发生异常: {e}")
            self.emergency_cleanup()
            return False
    
    def _display_final_results(self, deployment_results, verification_results):
        """显示最终结果"""
        print("\n" + "="*70)
        print("🎯 终极测试结果汇总")
        print("="*70)
        
        # 部署结果
        deploy_success = sum(deployment_results.values())
        deploy_total = len(deployment_results)
        if deploy_total > 0:
            deploy_rate = deploy_success/deploy_total*100
            print(f"🚀 部署结果: {deploy_success}/{deploy_total} ({deploy_rate:.1f}%)")
        else:
            print("🚀 部署结果: 0/0 (0.0%)")
        
        for mechanism, result in deployment_results.items():
            status = "✅" if result else "❌"
            print(f"   {status} {mechanism}")
        
        print()
        
        # 验证结果
        verify_success = sum(verification_results.values())
        verify_total = len(verification_results)
        if verify_total > 0:
            verify_rate = verify_success/verify_total*100
            print(f"🔍 验证结果: {verify_success}/{verify_total} ({verify_rate:.1f}%)")
        else:
            print("🔍 验证结果: 0/0 (0.0%)")
        
        for mechanism, result in verification_results.items():
            status = "✅" if result else "❌"
            print(f"   {status} {mechanism}")
        
        print()
        
        # 总体评估
        overall_success = min(deploy_success, verify_success)
        overall_total = max(deploy_total, verify_total)
        overall_rate = overall_success / overall_total * 100 if overall_total > 0 else 0
        
        if overall_rate >= 90:
            grade = "🏆 优秀"
        elif overall_rate >= 80:
            grade = "🥇 良好"
        elif overall_rate >= 70:
            grade = "🥈 一般"
        else:
            grade = "🥉 需改进"
        
        print(f"📊 总体评估: {overall_success}/{overall_total} ({overall_rate:.1f}%) - {grade}")
        print()
        
        # 操作提示
        print("🛠️ 后续操作:")
        print("   1. 查看详细报告: cat /tmp/persistence_test_report_*.md")
        print("   2. 清理测试环境: python3 ultimate_persistence_tester.py --cleanup")
        print("   3. 重新运行测试: python3 ultimate_persistence_tester.py --test")
        print("="*70)

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='终极Linux持久化测试器 v2.0')
    parser.add_argument('--test', action='store_true', help='运行完整测试')
    parser.add_argument('--cleanup', action='store_true', help='仅执行清理')
    parser.add_argument('--verify', action='store_true', help='仅执行验证')
    parser.add_argument('--report', action='store_true', help='生成测试报告')
    
    args = parser.parse_args()
    
    tester = UltimatePersistenceTester()
    
    try:
        if args.cleanup:
            tester.cleanup_all_mechanisms()
        elif args.verify:
            tester.verify_all_mechanisms()
        elif args.report:
            tester.generate_comprehensive_report({}, {})
        else:
            # 默认运行完整测试
            success = tester.run_ultimate_test()
            
            # 询问是否清理
            try:
                response = input("\n🤔 是否立即清理测试环境? (y/N): ").strip().lower()
                if response in ['y', 'yes']:
                    tester.cleanup_all_mechanisms()
                else:
                    print("💡 稍后可使用 --cleanup 参数清理环境")
            except KeyboardInterrupt:
                print("\n🧹 执行紧急清理...")
                tester.emergency_cleanup()
            
            return 0 if success else 1
            
    except Exception as e:
        tester.logger.error(f"❌ 程序异常: {e}")
        tester.emergency_cleanup()
        return 1

if __name__ == '__main__':
    sys.exit(main())